/*
 * @Author: 吴世扬 18368095041@163.com
 * @Date: 2024-10-14 16:08:29
 * @LastEditors: 吴世扬 18368095041@163.com
 * @LastEditTime: 2024-10-16 11:02:02
 * @FilePath: /react18-vite-admin/src/views/system/UsersManage/components/useForm.tsx
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */

import { useEffect, useState } from 'react';
import type { FormInstance } from 'antd';
import { immerable } from 'immer';
import { useImmer } from 'use-immer';

import { useUserDetail } from '@/service/biz/user/useUserDetail';
import { useEnumStore } from '@/store';

class FormModel {
    [immerable] = true;
    id?: number;
    username = '';
    valid = true;
    roleId?: number;
    departmentId?: number;
}

export const useForm = (formRef: FormInstance, id: number | undefined, open: boolean, afterSubmit: () => void) => {
    const [title, setTitle] = useState('新增');

    const { saveUser, getDetail, loading, saveLoading } =
        useUserDetail();

    const [formModel, setFormModel] = useImmer(new FormModel());

    const { roleType, deptTreeItems, handleUpdate } = useEnumStore();

    useEffect(() => {
        if (open) {
            formRef.resetFields();
            handleUpdate(['roleType', 'deptTreeItems']);
            handleEdit(id);
        }
    }, [open]);

    const handleEdit = async (id?: number) => {
        const model = new FormModel();
        if (id) {
            setTitle('编辑');
            const res = await getDetail(id);
            model.id = res?.data.id;
            model.username = res?.data.username ?? '';
            model.valid = res?.data.valid ?? false;
            model.roleId =
                res?.data.roleList && res.data.roleList[0]
                    ? res.data.roleList[0].id
                    : undefined;
            model.departmentId =
                res?.data.departmentList && res.data.departmentList[0]
                    ? res.data.departmentList[0].id
                    : undefined;
        } else {
            setTitle('新增');
        }
        setFormModel(model);
        formRef.setFieldsValue(model);
    };

    const handleSubmit = async () => {
        console.log(formModel);
        await saveUser({
            id: formModel.id,
            username: formModel.username,
            valid: formModel.valid,
            roleIdList: formModel.roleId ? [formModel.roleId] : [],
            departmentIdList: formModel.departmentId
                ? [formModel.departmentId]
                : []
        });
        afterSubmit();
    };

    return {
        title,
        handleSubmit,
        handleEdit,
        formModel,
        setFormModel,
        roleType,
        deptTreeItems,
        loading,
        saveLoading
    };
};
